package me.pearjelly.util;

import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.jpeg.JpegDirectory;

public class JpegMetadataUtil {
	public static int getWith(Metadata metadata) {
		try {
			Directory jpegDirectory = metadata
					.getDirectory(JpegDirectory.class);
			return Integer.parseInt(jpegDirectory
					.getString(JpegDirectory.TAG_JPEG_IMAGE_WIDTH));
		} catch (Exception e) {
			logger.error(e.getMessage());
			return 0;
		}
	}

	public static int getHeight(Metadata metadata) {
		try {

			Directory jpegDirectory = metadata
					.getDirectory(JpegDirectory.class);
			return Integer.parseInt(jpegDirectory
					.getString(JpegDirectory.TAG_JPEG_IMAGE_HEIGHT));
		} catch (Exception e) {
			logger.error(e.getMessage());
			return 0;
		}
	}

	public static int getPrecision(Metadata metadata) {
		try {
			Directory jpegDirectory = metadata
					.getDirectory(JpegDirectory.class);
			return Integer.parseInt(jpegDirectory
					.getString(JpegDirectory.TAG_JPEG_DATA_PRECISION));
		} catch (Exception e) {
			logger.error(e.getMessage());
			return 0;
		}
	}

	public static int getComponentsNumber(Metadata metadata) {
		try {
			Directory jpegDirectory = metadata
					.getDirectory(JpegDirectory.class);
			return Integer.parseInt(jpegDirectory
					.getString(JpegDirectory.TAG_JPEG_NUMBER_OF_COMPONENTS));
		} catch (Exception e) {
			logger.error(e.getMessage());
			return 0;
		}
	}

	public static Metadata readMetadata(InputStream inputStream) {
		try {
			return JpegMetadataReader.readMetadata(inputStream);
		} catch (JpegProcessingException e) {
			logger.error(e.getMessage());
			return null;
		}
	}

	private static final Logger logger = LoggerFactory
			.getLogger(JpegMetadataUtil.class);
}
